(function ($) {


    var defaultOption = {
        "listId": "msg-list",
        "titleId": "chat-title",
        "defaultImg": "./images/empty.png",
        "sendButtonId": "sendButton",
        "inputContentId": "inputContent",
        "onSend": function () {
            return true;
        }
    };

    window.ChatListView = function (config) {
        this.option = $.extend({}, defaultOption, config);
    };

    var init = function () {
        this.list = $("#" + this.option.listId);
        this.title = $("#" + this.option.titleId);
        this.sendButton = $("#" + this.option.sendButtonId);
        this.inputContent = $("#" + this.option.inputContentId);
        this.defaultImg = this.option.defaultImg;
        var onSendCallBack = this.option.onSend;
        var inputContent = this.inputContent;
        var list = this.list;
        this.sendButton.click(function () {
            var content = inputContent.val();
            if (onSendCallBack(content)) {
                inputContent.val("");
            }
        });

        inputContent.focus(function () {
            setTimeout(function () {
                scrollBottom(list);
            }, 500);
        });
        return this;
    };

    var clear = function () {
        this.list.empty();
        return this;
    };

    var setTitle = function (title) {
        this.title.html(title);
        return this;
    };

    var scrollBottom = function (elem) {
        // hack code
        var scrollHeight = 2147483647;
        //noinspection JSValidateTypes
        elem.scrollTop(scrollHeight);
    };

    var add = function (text, userImg, self) {
        var html = buildItem(text, userImg || this.defaultImg, self);
        this.list.append(html);
        scrollBottom(this.list);
        return this;
    };


    var buildItem = function (text, userImg, self) {
        text = text || "&nbsp;&nbsp;";
        var item = $('<div class="msg-item">');
        if (self) {
            item.addClass("msg-item-self");
        }
        var headImg = $('<img class="msg-user-img" src="" />');
        headImg.attr("src", userImg);
        item.append(headImg);
        var content = $('<div class="msg-content"></div>');
        content.append('<div class="msg-content-inner">' + text + '</div>');
        content.append('<div class="msg-content-arrow"></div>');
        item.append(content);
        item.append('<div class="mui-item-clear"></div>');
        return item;
    };


    ChatListView.prototype = {
        "init": init,
        "clear": clear,
        "add": add,
        "setTitle": setTitle
    };


})(window.jQuery);




